iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 3
0
Software Development

LeetCode刷題日記系列 第 19

【Day 19】#34 - Find First and Last Position of Element in Sorted Array

  • 分享至 

  • xImage
  •  

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

解析

此題要求給定數字在字串中的起始位置

解法

class Solution:
    # returns leftmost (or rightmost) index at which `target` should be inserted in sorted
    # array `nums` via binary search.
    def extreme_insertion_index(self, nums, target, left):
        lo = 0
        hi = len(nums)-1

        while lo < hi:
            mid = (lo + hi) // 2
            if nums[mid] > target or (left and target == nums[mid]):
                hi = mid
            else:
                lo = mid

        return lo   

    def searchRange(self, nums, target):
        
        # if target not in nums: 不能這樣做列表搜尋,因為其時間複雜度為O(n)
            # return [-1,-1]
        left_idx = self.extreme_insertion_index(nums, target, True)

        # assert that `left_idx` is within the array bounds and that `target` is actually in `nums`.
        if left_idx == len(nums) or nums[left_idx] != target:
            return [-1, -1]

        return [left_idx, self.extreme_insertion_index(nums, target, False)]

備註


希望透過記錄解題的過程,可以對於資料結構及演算法等有更深一層的想法。
如有需訂正的地方歡迎告知,若有更好的解法也歡迎留言,謝謝。


上一篇
【Day 18】#14 - Longest Common Prefix
下一篇
【Day 20】#226 - Invert Binary Tree
系列文
LeetCode刷題日記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言